#include <semaphore.h>

#include "Thread.h"
#include "CurrentThread.h"
std::atomic_int Thread::numCreated_(0);

Thread::Thread(ThreadFunc func,const std::string& name)
    : started_(false)
    , joined_(false)
    , tid_(0)
    , func_(std::move(func))
    , name_(name)
{
        setDefaultName();
}
void Thread::setDefaultName()
{
    int num=++numCreated_;
    if(name_.empty())
    {
        char buf[30]={0};
        snprintf(buf,sizeof buf,"Thread%d",num);
        name_=buf;
    }
}
    
Thread::~Thread()
{
    if(started_&&!joined_)
    {
        thread_->detach(); // c++11 thread类提供设置线程分离的方法
    }
}

void Thread::start()
{
    started_=true;

    sem_t sem; // 信号量
    sem_init(&sem,false,0);
    // 阻塞主线程 知道新线程完成tid_赋值
    thread_=std::shared_ptr<std::thread>(new std::thread([&](){
    // 获取线程tid
    tid_=CurrentThread::tid();
    sem_post(&sem); // 唤醒主线程

    func_(); //开启一个新线程 专门执行该线程函数
    }));

    // 这里必须等待获取上面线程tid值
    sem_wait(&sem);
}
void Thread::join()
{
    joined_=true;
    thread_->join();

}


